import { useState } from 'react'
import { LoadMore } from '@mf2e/bamboo-ui-rn'

const useLoadBefore = (onFetch, enabled) => {
  const [state, setState] = useState(null)

  const onLoading = async () => {
    if (state === 'loading' || state === 'finish') return

    setState('loading')
    try {
      const isFinish = await onFetch?.()
      setState(isFinish ? 'finish' : null)
    } catch (e) {
      console.log(e)
      setState('fail')
    }
  }

  const onScrollEndDrag = (e) => {
    if (e.nativeEvent?.contentOffset.y <= 0) {
      onLoading()
    }
  }

  const ListHeaderComponent = () => {
    return state && <LoadMore state={state} onRetry={onLoading} bottomSpace={0} />
  }

  return enabled
    ? {
        onScrollEndDrag,
        ListHeaderComponent,
        overScrollMode: 'always',
      }
    : {}
}

export default useLoadBefore
